package com.xin.edu.registry.handler;


import com.xin.edu.registry.handler.impl.ZookeeperRegistryHandler;
import com.xin.edu.rpc.common.ConfigKeeper;
import com.xin.edu.rpc.common.registry.RpcRegistryHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Service;

/**
 * 注册中心工厂类
 * FactoryBean 工厂bean的运用：构建复杂的bean，返回的是getObjectType()方法返回的类型的bean;
 */
@Service
public class RpcRegistryFactory implements FactoryBean<RpcRegistryHandler>, DisposableBean {
    //服务注册与服务发现
    private RpcRegistryHandler rpcRegistryHandler;

    @Override
    public RpcRegistryHandler getObject() throws Exception {
        if (null != rpcRegistryHandler) {
            return rpcRegistryHandler;
        }
        rpcRegistryHandler = new ZookeeperRegistryHandler(ConfigKeeper.getInstance().getZkAddr());
        return rpcRegistryHandler;
    }

    @Override
    public Class<?> getObjectType() {
        return RpcRegistryHandler.class;
    }

    @Override
    public void destroy() throws Exception {
        if (null != rpcRegistryHandler) {
            rpcRegistryHandler.destroy();
        }
    }
}
